﻿$('#lf_body').css('height', parseInt($('#detail_container').css('height'), 10) - parseInt($('#lf_top').css('height'), 10));

$('#detail_table_name').html($('#openning_table_name').val());

function show_notify(message) {
    $('#message_notify_msg').html(message);
    $('#message_notify').bPopup();
}

$('.row_item').click(function () {
    var td_check = $($(this).find('td')[0]).find('input');

    $(this).attr('sel', '1');
    $(td_check).click();
});

$('.lf_menu_grp_item').click(function () {
    var id = $(this).attr('value');

    var table = $('#lst_items');
    table.find('tr').each(function (index, row) {
        var allCells = $(row).find('td');
        if (allCells.length > 0) {
            var found = false;
            allCells.each(function (index, td) {
                if ($(td).attr('class') == 'f_groupid') {
                    if ($(td).html() == id) {
                        found = true;
                        return false;
                    }
                }
            });
            if (found == true) $(row).show(); else $(row).hide();
        }
    });
});

$('#serach_items').keyup(function () {
    searchTable($('#lst_items'), $(this).val());
});

function searchTable(table, inputVal) {
    table.find('tr').each(function (index, row) {
        var allCells = $(row).find('td');
        if (allCells.length > 0) {
            var found = false;
            allCells.each(function (index, td) {
                var regExp = new RegExp(inputVal, 'i');
                if (regExp.test($(td).text())) {
                    found = true;
                    return false;
                }
            });
            if (found == true) $(row).show(); else $(row).hide();
        }
    });
}

function addItem() {
    var table = $('#lst_items');
    var val = new Array();
    var idx = 0;

    table.find('tr').each(function (index, row) {
        if ($(row).attr('sel') == '1') {
            var itm = new Array();
            itm[0] = $(row).attr('value');
            itm[1] = $(row).attr('colls');
            val[idx] = itm;
            idx++;
        }
    });

    var tbl = $('#detail_list_menu');
    var _add_row = "";

    if (val.length > 0) {
        for (var i = 0; i < val.length; i++) {
            var found = false;
            tbl.find('tr').each(function (index, ro) {
                if ($(ro).attr('value') == val[i][0]) { /*Qty increment*/
                    var qty = $(ro).find('td.qty_cell')[0];
                    var _qty = Number($(qty).html()) + 1;
                    RecalcRow($(ro), _qty);

                    found = true;
                }
            });
            if (found == false) { /* insert row*/
                var its = val[i][1].split("#");
                _add_row = _add_row + "<tr value=" + val[i][0] + "><td>" + its[0] + "</td><td class='itm_name_cell'>" + its[1] + "</td><td class='itm_unit_id' value='" + its[2] + "'>" +
                            its[3] + "</td><td id='detail_row_qty_" + val[i][0] + "' class='qty_cell' onclick='ShowQtyChange(this);'>1</td><td class='price_cell'>" + format('#,###.##', its[4]) + "</td><td class='total_cell'>" + format('#,###.##', its[4]) +
                            "</td><td onclick='remove_row_detail(this);' style='width:16px;color:Red;'>x</td></tr>";
            }
        }
    }
    if (_add_row != undefined && _add_row != "") {
        $(tbl).append(_add_row);
        summaryTotal();
    }
}

function summaryTotal() {
    var tbl = $('#detail_list_menu');
    var _sum = 0;

    tbl.find('tr').each(function (index, row) {
        var _total = $(row).find('td.total_cell');
        if (_total != undefined && _total.length > 0) {
            _sum += Number($(_total).html().replace(',', ''));
        }
    });

    $('#summary_sub_total').val(format('#,###.##', _sum));
    $('#summary_dis_value').val(format('#,###.##', (_sum * Number($('#summary_dis_percent').val())) / 100));
    $('#summary_total').val(format('#,###.##',
        Number($('#summary_sub_total').val().replace(',', '')) - Number($('#summary_dis_value').val().replace(',', ''))));
}

function RecalcRow(obj, value) {
    var qty = $(obj).find('td.qty_cell')[0];
    var _qty = value;

    $(qty).html(_qty);

    var _price = Number($($(obj).find('td.price_cell')[0]).html().replace(',', ''));
    $($(obj).find('td.total_cell')[0]).html(format('#,###.##', _qty * _price));

    summaryTotal();
}

$('#summary_payment').change(function () {
    var _val = Number($(this).val().replace(',', '')) - Number($('#summary_sub_total').val().replace(',', ''));

    if (_val < 0) {
        return;
    }
    $('#summary_repay').val(format('#,###.##', _val));
});

/*Number link clicked*/
function Payment(value) {
    $('#summary_payment').val(format('#,###.##', value));
    $('#summary_payment').change();
}

function ShowQtyChange(obj) {
    $('#input_text_change_qty').val($(obj).html());
    $('#qty_change').attr('elementid', $(obj).attr('id'));

    $('#qty_change').bPopup();
}

$('#input_btn_plus_qty').click(function () {
    $('#input_text_change_qty').val(Number($('#input_text_change_qty').val()) + 1);
});
$('#input_btn_minus_qty').click(function () {
    if (Number($('#input_text_change_qty').val()) > 0)
        $('#input_text_change_qty').val(Number($('#input_text_change_qty').val()) - 1);
});
$('#input_btn_accept_qty').click(function () {
    var obj = $('#qty_change').attr('elementid');

    if (obj != undefined && obj != "") {
        $('#' + obj).html(Number($('#input_text_change_qty').val()));
        $('#qty_change').bPopup().close();

        if (obj.substring(0, 15) == 'detail_row_qty_') {
            RecalcRow($($('#' + obj).parent()), Number($('#input_text_change_qty').val()));
        }
    }
});

/*End change qty*/

function remove_row_detail(obj) {
    var _itm = $($(obj).parent()).find('td.itm_name_cell')[0];
    $('#remove_row_itm_name_msg').html($(_itm).html());
    $('#message_remove_row').bPopup({
        onClose: function () {
            if ($('#message_remove_row').attr("value") == "1") {
                $($(obj).parent()).remove();
            }
        }
    });
}

function close_message(value) {
    $('#message_remove_row').attr("value", value);
    $('#message_remove_row').bPopup().close();
}

function close_notify() {
    $('#message_notify').bPopup().close();
}

$('#lf_top').click(function () {
    if ($("#detail_left_menu").css('width') == '50px') {
        $("#detail_left_menu").css('width', '600px');
    }
    else {
        $("#detail_left_menu")
            .css("width", -$(this).width())
            .animate({
                width: 50
            }, 500);
    }
});

/*Button click events*/
$('#btn_new').click(function () {
    /*If allow new*/
    $('#summary_sub_total').val('0');
    $('#summary_dis_percent').val('0');
    $('#summary_dis_value').val('0');
    $('#summary_total').val('0');
    $('#summary_payment').val('0');
    $('#summary_repay').val('0');

    $('#f_date').datetimepicker('setDate', new Date());

    $('#detail_list_menu').find('tr').each(function (index, row) {
        if ($(row).attr('value') != undefined && $(row).attr('value') != null) {
            $(row).remove();
        }
    });
});
$('#btn_save').click(function () {
    var idbanhang = Number($('#detail_data').attr('saleid'));
    var idban = Number($('#detail_data').attr('tblid'));
    var thanhtien = Number($('#summary_sub_total').val().replace(',', ''));
    var pt_ck = Number($('#summary_dis_percent').val().replace(',', ''));
    var tien_ck = Number($('#summary_dis_value').val().replace(',', ''));
    var tongtien = Number($('#summary_total').val().replace(',', ''));
    var khachtra = Number($('#summary_payment').val().replace(',', ''));

    var _date = $('#f_date').val().split(' ');
    var arr1 = _date[0].split('/');
    var arr2 = _date[1].split(':');

    var onDate = arr1[1] + '/' + arr1[0] + '/' + arr1[2] + ' ' + arr2[0] + ':' + arr2[1] + ':00';

    var _items = new Array();
    var idx = 0;

    $('#detail_list_menu').find('tr').each(function (index, row) {
        var _row = '';
        if ($(row).attr('value') != undefined && $(row).attr('value') != null) {
            _row += $(row).attr('value') + '#' + $($(row).find('td.itm_unit_id')[0]).attr('value') + '#' +
                $($(row).find('td.qty_cell')[0]).html() + '#' + $($(row).find('td.price_cell')[0]).html() + '#' +
                $($(row).find('td.total_cell')[0]).html();
            _items[idx] = _row;
            idx++;
        }
    });

    if (_items != null && _items.length > 0) {
        $.ajax({
            url: "/Home/UpdateData/",
            dataType: "json",
            cache: false,
            type: 'GET',
            traditional: true, /*Pass array condition*/
            data: { IdBanHang: idbanhang, IdBan: idban, Ngay: onDate, ThanhTien: thanhtien, PT_CK: pt_ck, TienCK: tien_ck, TongTien: tongtien, KhachTra: khachtra, Detail: _items },
            success: function (result) {
                if (result.Success) {
                    show_notify('Cập nhật thành công.');
                }
                else {
                    show_notify(result.Err);
                }
            }
        });
    }
});
$('#btn_print').click(function () {
    alert('print');
});
$('#btn_del').click(function () {
    $.ajax({
        url: "/Home/OnDelete/",
        dataType: "json",
        cache: false,
        type: 'GET',
        data: { IdBanHang: Number($('#detail_data').attr('saleid')) },
        success: function (result) {
            if (result.Success) {
                $('#btn_new').click();
            }
            else {
                show_notify(result.Err);
            }
        }
    });
});
$('#btn_home').click(function () {
    $('#detail_container').css('display', 'none');
});
/*End button click*/

$('#group_split_table').click(function () {
    $('#f_tbl_items').children().remove();
    $('#tbl_f_loaction').children().remove();
    $('#find_tbl_container').find('table.f_tbl_items').remove();
    $('#f_find_item').val('');
    $('#f_itm_selected').attr('value', '0');
    $('#f_itm_selected').html('--?--');

    $.ajax({
        url: "/Home/GetTableAndLocation/",
        dataType: "json",
        cache: false,
        type: 'GET',
        data: {},
        success: function (result) {
            if (result.Success) {
                $('#tbl_f_loaction').append("<tr>");
                var data = result.data.ViTriBan;
                var _itms = result.data.Ban;

                for (var i = 0; i < data.length; i++) {
                    $('#tbl_f_loaction').append("<td value=" + data[i].Value + " onclick='f_location_click(this);'>" + data[i].Text + "</td>");

                    var _tbl = "<table class='f_tbl_items' value='" + data[i].Value + "'>";
                    var _idx = 0;
                    for (var j = 0; j < _itms.length; j++) {
                        if (_itms[j].IdViTri == data[i].Value) {
                            if (_idx == 0 || (_idx > 0 && _idx % 5 == 0)) {
                                _tbl += "<tr>";
                            }

                            _tbl += "<td value='" + _itms[j].IdBan + "' txt='" + _itms[j].TenBan + "' onclick='f_item_click(this);'> <div class='item_detail'>";
                            _tbl += "<img src='" + ((_itms[j].State > 0) ? '/Content/Themes/Fontend/images/tbl2.png' : '/Content/Themes/Fontend/images/tbl.png') + "'>";
                            _tbl += "<span class='tbl_item_name'>" + _itms[j].TenBan + "</span";
                            _tbl += "</div></td>";

                            if (_idx > 0 && (_idx + 1) % 5 == 0) {
                                _tbl += "</tr>";
                            }

                            _idx++;
                        }
                    }
                    _tbl += "</table>";
                    $('#find_tbl_container').append(_tbl);
                }
                $('#tbl_f_loaction').append("</tr>");

                $($('#find_tbl_container').find('table.f_tbl_items')[0]).css('display', 'block'); /*First location*/
            }
        }
    });

    $('#find_tbl_container').bPopup();
});

function f_location_click(obj) {
    $('#find_tbl_container').find('table.f_tbl_items').each(function (index, tbl) {
        if ($(tbl).attr('value') == $(obj).attr('value'))
            $(tbl).css('display', 'block');
        else
            $(tbl).css('display', 'none');
    });
}

function f_item_click(obj) {
    $('#f_itm_selected').attr('value', $(obj).attr('value'));
    $('#f_itm_selected').html($(obj).attr('txt'));
}

function tbl_sel_ms_accept() {
    $('#find_tbl_container').bPopup().close();
    if ($('#f_itm_selected').attr('value') != '' && $('#f_itm_selected').attr('value') != '0') {
        $('#table_move_from').html($('#openning_table_name').val());
        $('#table_move_to').html($('#f_itm_selected').html());
        $('#tbl_ms_detail').bPopup();
    }
}

$('#f_find_item').keyup(function () {
    $('#find_tbl_container').find('table.f_tbl_items').each(function (index, tbl) {
        if ($(tbl).css('display') == 'block') {
            $(tbl).find('tr').each(function (index, row) {
                var allCells = $(row).find('td');
                if (allCells.length > 0) {
                    allCells.each(function (index, td) {
                        var regExp = new RegExp($('#f_find_item').val(), 'i');
                        var txt = $(td).attr('txt');
                        if (!regExp.test(txt)) {
                            $(td).hide();
                        }
                        else
                            $(td).show();
                    });
                }
            });
        }
    });
});

function rdo_uncheck(obj) {
    var _sp = $($(obj).find('span')[0]);
    $(_sp).removeClass('rdo_checked');
    $(_sp).addClass('rdo_normal');
}

$('.radio_button').click(function () {
    $($(this).parent()).find('p').each(function (index, itm) {
        rdo_uncheck($(itm));
    });

    var _frs = $(this).find('span')[0];
    $(_frs).removeClass('rdo_normal');
    $(_frs).addClass('rdo_checked');
    $($(this).parent()).attr('value', $(this).attr('def'));
});

/*table merge/split detail choose menu*/
$('#tbl_ms_dtl_sel_menu').click(function () {
    var id = $('#detail_data').attr('saleid');
    var tbl = $('#tbl_ms_dtl_itms');
    $(tbl).find("tr:gt(0)").remove();
    var _htm = "";
    
    $.ajax({
        url: "/Home/GetDetail/",
        dataType: "json",
        cache: false,
        type: 'GET',
        data: { id: Number(id) },
        success: function (result) {
            if (result.Success) {
                var _db = result.data;
                if (_db != null && _db != undefined && _db.length > 0) {
                    for (var i = 0; i < _db.length; i++) {
                        _htm += "<tr><td>" + _db[i].HangHoa.TenHang + "</td><td>" + _db[i].DVT.TenDVT + "</td><td id='move_qty_" + _db[i].HangHoa.IdHangHoa + "' onclick=ShowQtyChange(this);>" + _db[i].SoLuong + "</td></tr>";
                    }
                    $(tbl).append(_htm);
                }
            }
        }
    });
});

$('#tlb_ms_dtl_all_menu').click(function () {
    $('#tbl_ms_dtl_itms').find("tr:gt(0)").remove();
})

function tbl_ms_dtl_op1_click(value) {
    if (value == 1) {
        $('#tbl_ms_dtl_op2').css('display', 'none');
    }
    else {
        $('#tbl_ms_dtl_op2').css('display', 'block');
    }
}